package com.chaochis.springboottestdemo.service.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.chaochis.springboottestdemo.model.mapperModel.UserVo;
import com.chaochis.springboottestdemo.service.JwtTokenService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Date;

@Service("jwtTokenService")
public class JwtTokenServiceImpl implements JwtTokenService {
  @Override
  public String generateJwtTokenString(UserVo userVo, Duration duration) throws Exception {
    var token = "";
    if (StringUtils.isBlank(userVo.getUserName())) {
      throw new Exception("生成token时提供的用户名不能为空!");
    }
    var seconds = (Long)duration.getSeconds();
    Date expireDate = DateUtils.addSeconds(new Date(), seconds.intValue());
    Algorithm algorithm = Algorithm.HMAC256(userVo.getSalt());
    var jwt = JWT.create();
    jwt.withClaim("userName", userVo.getUserName());
    jwt.withIssuer("cc");
    jwt.withIssuedAt(new Date());
    jwt.withExpiresAt(expireDate);
    token = jwt.sign(algorithm);
    return token;
  }

}
